/**
 *data_param:请求数据参数
 *url ：请求地址
 */

function callServlet (data_param,url){
	var result = new Object();
	var obj = new Object();
	var param = JSON.stringify(data_param);
	var aeskey = randPassword();
	var cbciv = randPassword();
	var pubkey = {aeskey:aeskey, cbciv:cbciv};
	//AES加密密文
	obj.enData = encryptByAESCBC(param, aeskey, cbciv);
	obj.enPW = encryptByRsa(JSON.stringify(pubkey));

	Ext.Ajax.request({
		method: 'POST',
		async: true,
		url: url,
		timeout:60000,
		params: obj,
		failure: util.ajax.failure,
		success: function (r, o) {
			result=r.responseText && r.responseText != '' ? Ext.util.JSON.decode(decrypByAESCBC(r.responseText,aeskey,cbciv)) : null;
			return  result;
		}
	});

	// $.ajax({
	// 	type: "POST",
	// 	url: url,
	// 	timeout:60000,
	// 	data:obj,
	// 	dataType: "json",
	// 	async:false,
	// 	beforeSend :function(XMLHttpRequest){
	//
	// 	},
	// 	success: function(data){
	// 		result = decrypByAESCBC(data.data.result, aeskey, cbciv);
	// 	},
	// 	error: function(XMLHttpRequest, textStatus, errorThrown) {
	//
	// 	},
	// 	complete:function(XMLHttpRequest,status){
	// 		if(status == "timeout"){
	// 			//超时
	// 			ajaxTimeoutTest.abort();
	// 			alert("超时");
	// 		}
	// 	}
	// });
	return result;
};

/**
 * 获取数据加密密文
 * @param data_param
 * @returns {Object}
 */
function getEncryptReqParam(data_param){
	var encData = new Object();
	var param = JSON.stringify(data_param);
	var aesKey = randPassword();
	var cbcIV = randPassword();
	var pubKey = {
			"aeskey":aesKey,
			"cbciv":cbcIV
	};
	//AES加密密文
	encData.enData = encryptByAESCBC(param, aesKey, cbcIV);
	encData.enPW = encryptByRsa(JSON.stringify(pubKey));
	encData.pubKey = pubKey;
	return encData;
}

/**
 * 解密返回数据
 * @param targetStr
 */
function decryptReturnValue(targetStr, publicKey){
	return decrypByAESCBC(targetStr, publicKey["aeskey"], publicKey["cbciv"]);
}

/**
 * 随机生成32位的des密码
 * zhanghao
 * @returns
 */
function randPassword() {
	var text=['abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ','1234567890','~!@#$%^*_.?']; 
	var rand = function(min, max){
		return Math.floor(Math.max(min, Math.random() * (max+1)));
	};
	var len = 16; 
	var pw = ''; 
	for(var i=0; i<len; i++){
		var strpos = rand(0, 3); 
		pw += text[strpos].charAt(rand(0, text[strpos].length-1)); 
	} 
	return "9AH#B2D*k4n6@#N1"; 
}

/** * AES加密（CBC模式，需要偏移量） * @param data * @returns {*} */
function encryptByAESCBC(data, aeskey, cbciv) {
	var keyHex = CryptoJS.enc.Utf8.parse(aeskey);    
	var secretData = CryptoJS.enc.Utf8.parse(data);
	// 加密选项
	var CBCOptions = {
		iv: CryptoJS.enc.Utf8.parse(cbciv),	
		mode: CryptoJS.mode.CBC,	
		padding: CryptoJS.pad.Pkcs7
	};
	var encrypted = CryptoJS.AES.encrypt(secretData, keyHex, CBCOptions);
	return encrypted.toString();
}


/**
 * 密钥加密
 * zhanghao
 * @returns
 */
function encryptByRsa(param){
	var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDpjILs6d8MYDM8jgqg9n7Ot+nEUKGajO+6+nb3m7B38t8ZQHmxSvknY7T1dyFyzYBPgc25Y4AWfJPQiVF+Xcq5jB1MD3qRlyDg5RM6cNv1oNFWGkEMFM0JYjCpxJYRKUE8tEkUc0LcCwF69XCHpm65AeXTtXfUmPlCnd5xSf/XmwIDAQAB";
	var encrypt = new JSEncrypt();
	encrypt.setPublicKey(publicKey);
	var aesKey = randPassword();
	var cbcIV = randPassword();
	var pubKey = {
		"aeskey":aesKey,
		 "cbciv":cbcIV,
		"salt": new Date().getTime()
		
	};
	var enData = encrypt.encrypt(JSON.stringify(pubKey));
	return enData;
}

/** 
 * AES解密（CBC模式，需要偏移量） 
 * zhanghao
 * @param data * @returns {*} 
 */
function decrypByAESCBC(data, aeskey, cbciv){
	var keyHex = CryptoJS.enc.Utf8.parse(aeskey);
	// 加密选项
	var CBCOptions = {
		iv: CryptoJS.enc.Utf8.parse(cbciv),	
		mode:CryptoJS.mode.CBC,	
		padding: CryptoJS.pad.Pkcs7
	}
	//var base64 = CryptoJS.enc.Base64.parse(data);
	//var src = CryptoJS.enc.Utf8.stringify(data);
	var decrypt = CryptoJS.AES.decrypt(data, keyHex, CBCOptions);
	return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

/**
 * 加密传输数据
 * 使用post请求，传输json格式数据
 * 如需调用请对接口进行适应性改造
 * @param url
 * @param reqParam
 * @param successHandle
 * @param errorHandle
 */
function ajaxEncrypt(url, reqParam, successHandle, errorHandle){
	var encData = getEncryptReqParam(reqParam);
	var publicKey = encData.pubKey;
	delete encData["pubKey"];

	Ext.Ajax.request({
		method: 'POST',
		async: true,
		url: url,
		timeout:60000,
		params: encData,
		failure: errorHandle,
		success: function (r, o) {
			var respJSON = JSON.parse(decryptReturnValue(r.responseText, publicKey));
			successHandle(respJSON["entity"]);
		}
	});

	// $.ajax({
	// 	"url": url,
	// 	"dataType": 'json',
	// 	"type": "post",
	// 	"async": false,
	// 	"contentType": "application/json; charset=utf-8",
	// 	"data": JSON.stringify(encData),
	// 	"success": function(resp){
	// 		var respJSON = JSON.parse(decryptReturnValue(resp, publicKey));
	// 		successHandle(respJSON["entity"]);
	// 	},
	// 	"error": errorHandle
	// });
}

/**
 *对Date的扩展，将 Date 转化为指定格式的String
 *月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *例子：
 *(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 */
Date.prototype.format = function (fmt) {
	let o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (let k in o){
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
};

/**
 * 日期格式化(数组)
 * @param dataArray
 * @param formatField
 * @returns {*}
 */
function formatArrayForDate(dataArray, formatFields){
    if(checkFormatDataType(dataArray)){
        return dataArray;
    }
	for(let i = 0;i < dataArray.length;i++){
		let target = dataArray[i];
		formatDateField(target, formatFields);
	}
	return dataArray;
}

/**
 * 日期格式化（单条数据）
 * @param obj
 * @param formatField 需格式化字段名 ["", "", ...]
 * @returns {*}
 */
function formatDateField(obj, formatFields){
	if(checkFormatDataType(obj)){
		return obj;
	}
	for(let j = 0;j < formatFields.length;j++){
		if(obj[formatFields[j]] == null || obj[formatFields[j]] == undefined ||
			obj[formatFields[j]] == '') {
			obj[formatFields[j]] = "";
			continue;
		}
		obj[formatFields[j]] = new Date(obj[formatFields[j]]).format("yyyy-MM-dd hh:mm:ss");
	}
	return obj;
}

/**
 * 检查传入数据是否正常
 */
function checkFormatDataType(obj){
	if(obj == null || obj == undefined || obj == ""
		|| typeof(obj) != 'object'){
		return true;
	}
	return false;
}
